package com.foreveross.crawl.adapter.sub.impl20140402.v3;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

import com.foreveross.crawl.adapter.AbstractAdapter;
import com.foreveross.crawl.adapter.PlaneInfoEntityBuilder;
import com.foreveross.crawl.common.exception.self.PageErrorResultException;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.TransitEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnTransitEntity;
import com.foreveross.taskservice.common.bean.TaskModel;
/**
 * 智游天下网适配器
 * <p>这里的备注很重要：现在的适配器，只取中转的最低价，以及直达的最低价(一个航班单程或往返)
 * @author xiangsf 2014-09-04
 *
 */
public class ExpediaAdapter extends AbstractAdapter {

	private final static boolean IS_FETCH_RETURN = true;//是否抓取返程
	private final static int FETCH_RETURN_COUNT = 2; //返程抓取失败时尝试次数
	public ExpediaAdapter(TaskModel taskQueue) {
		super(taskQueue);
	}

	@Override
	public String getUrl() throws Exception {
		StringBuilder sbuilder = new StringBuilder();
		sbuilder.append("http://www.expedia.com.hk/Flight-Search-All?");
		sbuilder.append("action=FlightSearchAll&origref=www.expedia.com.hk%2FFlight-Search-All");
		sbuilder.append("&inpFlightRouteType=2");
		sbuilder.append("&inpDepartureLocations=").append(taskQueue.getFromCity());
		sbuilder.append("&inpArrivalLocations=").append(taskQueue.getToCity());
		sbuilder.append("&inpDepartureDates=").append(
				URLEncoder.encode(taskQueue.getFlightDate().replaceAll("-", "/"), "utf-8"));
		sbuilder.append("&inpArrivalDates=").append(
				URLEncoder.encode(taskQueue.getReturnGrabDate().replaceAll("-", "/"), "utf-8"));
		sbuilder.append("&inpAdultCounts=1&inpChildCounts=0&inpChildAges=-1&inpChildAges=-1&inpChildAges=-1&inpChildAges=-1");
		sbuilder.append("&inpChildAges=-1&inpInfants=2&inpFlightAirlinePreference=&inpFlightClass=3");

		return sbuilder.toString();
	}
	/**
	 * 返程的URL组装
	 * @return
	 */
	private String getReturnUrl(){
		StringBuilder sbuilder = new StringBuilder();
		sbuilder.append("http://www.expedia.com.hk/Flight-Search-Update?");
		sbuilder.append("c=").append(continuationId);
		sbuilder.append("&tripId0=0");
		sbuilder.append("&_=").append(System.currentTimeMillis());
		return sbuilder.toString();
	}
	@Override
	public Object fetch(String url) throws Exception {
		HttpGet get = null;
		String html = null;
		String cCode = null;
		try{
			 get = new HttpGet(this.getUrl());
			 html = super.excuteRequest(get);
			 super.appendPageContents(html);
			 cCode = RegHtmlUtil.regStr(html, "<div id=\"originalContinuationId\">([0-9|a-z|-]{30,40})</div>");
			//http://www.expedia.com.hk/Flight-Search-Outbound?c=5ffdbf3e-15b8-4d41-98bf-966e446b1024&_=1409811714380
			get = new HttpGet(String.format("http://www.expedia.com.hk/Flight-Search-Outbound?c=%s&_=%s", cCode, 
					System.currentTimeMillis()));
			html = super.excuteRequest(get);
			super.appendPageContents(html);
		}finally{
			 get = null;
			 cCode = null;
		}
		return html;
	}

	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		if(fetchObject == null || fetchObject.toString().length()<2000){
			throw new PageErrorResultException("抓取到的数据不正确!");
		}
		return true;
	}
	private String continuationId, userInteractionDataAsJson;//公共变量，查询去程页面后的动态变量
	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		List<Object> results = new ArrayList<Object>();
		JSONObject j = JSONObject.fromObject(fetchObject.toString());
		continuationId = j.getString("continuationId");
		userInteractionDataAsJson = j.getString("userInteractionDataAsJson");
		j = j.getJSONObject("searchResultsModel");
		JSONArray ja = j.getJSONArray("offers");
		//获取到的数据本身已经是按价格由低到高排序，所以获得的第一条数据即是航线最低价
		//获得一条中转的
		results.addAll(this.parseGoInfo(ja, true));
		//获得一条直达的
		results.addAll(this.parseGoInfo(ja, false));

		return results;
	}
	
	private List<ReturnDoublePlaneInfoEntity> fetchReturn(JSONObject leg) throws Exception{
		String userUrl = null;
		Map<String, String> params = null;
		HttpPost post = null;
		HttpGet get = null;
		String html = null;
		JSONObject j = null;
		JSONArray ja = null;
		try{	
			if(super.isUseProxyip()) Thread.sleep(5000);
			 userUrl = "http://www.expedia.com.hk/UserInteraction/LogUserInteraction";
			//continuationId : "2c12b363-b099-4ee6-bdb0-fba6232f304f"
			//{"context":{"user":{"guid":"63efb79f-009c-4772-a2a0-5ded0ee8c397","tuid":"-1","expUserProfileId":-1,"registered":false,"userType":"ANONYMOUS"},"site":{"siteId":18,"eapid":0,"tpid":18},"sessionId":"3526fb7b-e448-4b1b-8864-d80c676df60a","clientInfo":{"userAgent":"Chrome","os":"Win7","ipAddress":"120.197.59.144"},"channelType":"Desktop","parentRequestId":"dbaa4b03-04ac-47f9-a71f-849a6d6be206","tests":[{"testId":5586,"value":0,"testInstanceId":22754,"experimentId":5586,"bucketValue":0,"instanceId":22754},{"testId":5539,"value":1,"testInstanceId":22474,"experimentId":5539,"bucketValue":1,"instanceId":22474},{"testId":5462,"value":2,"testInstanceId":22583,"experimentId":5462,"bucketValue":2,"instanceId":22583},{"testId":3526,"value":0,"testInstanceId":14811,"experimentId":3526,"bucketValue":0,"instanceId":14811},{"testId":99991,"value":0,"testInstanceId":99990,"experimentId":99991,"bucketValue":0,"instanceId":99990},{"testId":5643,"value":0,"testInstanceId":22696,"experimentId":5643,"bucketValue":0,"instanceId":22696}],"channelName":"ExpediaWeb","sourceName":"ExpediaWeb"},"utcTimestamp":1409883301900,"entity":{"productTypes":["AIR"],"flightSearch":{"searchParameters":{"departureAirport":"XMN","arrivalAirport":"SIN","departureDate":"Sun Sep 21 06:02:00 PDT 2014","returnDate":"Tue Sep 30 06:02:00 PDT 2014","nonStop":false,"refundable":false,"preferredAirline":"","travelClass":"ECONOMY_COACH_CLASS"},"travelers":{"numberOfAdults":1,"numberOfSeniors":0,"numberOfChildren":0,"childAges":[],"numberOfInfantsInLap":0},"searchResults":{"cheapest":{"price":{"currency":"HKD","amount":3249,"decimalAmountString":"3249.00"},"durationInMinutes":30,"offerToken":"0","numberOfSeatsLeft":7,"splitTicket":false},"shortest":{"price":{"currency":"HKD","amount":3458,"decimalAmountString":"3458.00"},"durationInMinutes":10,"offerToken":"1","numberOfSeatsLeft":9,"splitTicket":false},"numberOfSearchResults":23,"splitTicketAvailable":false},"searchType":"page.Flight-Search-Roundtrip.Out","pointOfSupplyTime":"2014-09-05T10:15:01.900+08:00","utcPointOfSupplyTimestamp":0},    "pageInfo":{"pageName":"page.Flight-Search-Roundtrip.Out","errorCodes":[]},"version":"v1","domain":"AIR","action":"FLIGHT_SELECT",
				//"flight":{"flight":{"flight":{"legs":[{"legId":1,"departureAirportCode":"XMN","arrivalAirportCode":"SIN","utcDepartureTimestamp":1411278300000,"utcArrivalTimestamp":1411309800000,"stopCount":1,"totalDurationInMinutes":525,"segments":[{"departureAirportCode":"XMN","arrivalAirportCode":"CAN","carrierCode":"CZ","operatingCarrierCode":"","flightNumber":"3742","totalDurationInMinutes":65,"utcDepartureTimestamp":1411278300000,"utcArrivalTimestamp":1411282200000,"stopOver":false},{"departureAirportCode":"CAN","arrivalAirportCode":"SIN","carrierCode":"CZ","operatingCarrierCode":"","flightNumber":"351","totalDurationInMinutes":240,"utcDepartureTimestamp":1411295400000,"utcArrivalTimestamp":1411309800000,"stopOver":false}],"legPosition":0}]},"pricePerTraveler":{"currency":"HKD","amount":3765},"totalPrice":{"currency":"HKD","amount":3765}}}}}
			//{"context":{"user":{"guid":"31923a9a-d8f3-4291-9900-2b9f0ffd23ae","tuid":"-1","expUserProfileId":-1,"registered":false,"userType":"ANONYMOUS"},"site":{"siteId":18,"eapid":0,"tpid":18},"sessionId":"de508e64-e6f7-4207-a9b9-f5298df20e6c","clientInfo":{"userAgent":"DefaultProperties","ipAddress":"120.197.59.144"},"channelType":"Desktop","parentRequestId":"688bd485-7853-4dfa-89e4-5b98113ca067","tests":[{"testId":5586,"value":1,"testInstanceId":22754,"experimentId":5586,"bucketValue":1,"instanceId":22754},{"testId":5539,"value":1,"testInstanceId":22474,"experimentId":5539,"bucketValue":1,"instanceId":22474},{"testId":5462,"value":2,"testInstanceId":22583,"experimentId":5462,"bucketValue":2,"instanceId":22583},{"testId":3526,"value":0,"testInstanceId":14811,"experimentId":3526,"bucketValue":0,"instanceId":14811},{"testId":99991,"value":0,"testInstanceId":99990,"experimentId":99991,"bucketValue":0,"instanceId":99990},{"testId":5643,"value":0,"testInstanceId":22696,"experimentId":5643,"bucketValue":0,"instanceId":22696}],"channelName":"ExpediaWeb","sourceName":"ExpediaWeb"},"utcTimestamp":1409882843638,"entity":{"productTypes":["AIR"],"flightSearch":{"searchParameters":{"departureAirport":"XMN","arrivalAirport":"SIN","departureDate":"Sun Sep 21 06:02:00 PDT 2014","returnDate":"Tue Sep 30 06:02:00 PDT 2014","nonStop":false,"refundable":false,"preferredAirline":"","travelClass":"ECONOMY_COACH_CLASS"},"travelers":{"numberOfAdults":1,"numberOfSeniors":0,"numberOfChildren":0,"childAges":[],"numberOfInfantsInLap":0},"searchResults":{"cheapest":{"price":{"currency":"HKD","amount":3249.0,"decimalAmountString":"3249.00"},"durationInMinutes":30,"offerToken":"0","numberOfSeatsLeft":7,"splitTicket":false},"shortest":{"price":{"currency":"HKD","amount":3458.0,"decimalAmountString":"3458.00"},"durationInMinutes":10,"offerToken":"1","numberOfSeatsLeft":9,"splitTicket":false},"numberOfSearchResults":23,"splitTicketAvailable":false},"searchType":"page.Flight-Search-Roundtrip.Out","pointOfSupplyTime":"2014-09-05T10:07:23.638+08:00","utcPointOfSupplyTimestamp":0}},"pageInfo":{"pageName":"page.Flight-Search-Roundtrip.Out","errorCodes":[]},"version":"v1","domain":"AIR","action":"EMPTY"}"
			params = new HashMap<String, String>();
			params.put("userInteractionDataAsJson", this.buildRequestJSON(leg));
			 post = super.getBasePost(userUrl, params);
			super.excuteRequest(post);
	
			 get = new HttpGet(getReturnUrl());
			 html = super.excuteRequest(get);
			super.appendPageContents(html);
			//解析返程
			j = JSONObject.fromObject(html);
			j = j.getJSONObject("searchResultsModel");
			ja = j.getJSONArray("offers");
			return this.parseReturnInfo(ja);
		}finally{
			 userUrl = null;
			 params = null;
			 post = null;
			 get = null;
			 html = null;
			 j = null;
			 ja = null;
		}
	}
	/**
	 * 组装单个去程在点击“选择”返程按钮时的请求JSON数据
	 * @param leg
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String buildRequestJSON(JSONObject leg) throws UnsupportedEncodingException{
		JSONObject json = JSONObject.fromObject(userInteractionDataAsJson);
		json.put("action", "FLIGHT_SELECT");
		JSONObject entity = json.getJSONObject("entity");
		//第一个flight
		Map<String, Object> flight1 = new HashMap<String, Object>();
		
		//第二个flight
		Map<String, Object> flight2 = new HashMap<String, Object>();
		flight1.put("flight", flight2);
		//第三级flight, pricePerTraveler,totalPrice
		Map<String, Object> flight3 = new HashMap<String, Object>();
		Map<String, Object> pricePerTraveler = new HashMap<String, Object>();
		Map<String, Object> totalPrice = new HashMap<String, Object>();
		flight2.put("flight", flight3);
		flight2.put("pricePerTraveler", pricePerTraveler);
		flight2.put("totalPrice", totalPrice);
		
		//设置pricePerTraveler值
		pricePerTraveler.put("currency", leg.getJSONObject("price").getString("currencyCode"));
		pricePerTraveler.put("amount", leg.getJSONObject("price").getString("offerPrice"));
		//设置totalPrice值
		totalPrice.put("currency", leg.getJSONObject("price").getString("currencyCode"));
		totalPrice.put("amount", leg.getJSONObject("price").getString("offerPrice"));
		
		//设置实际flight(第三个)
		List<Object> legs = new ArrayList<Object>();//只有一个对象
		Map<String, Object> singleLeg = new HashMap<String, Object>();
		List<Object> segments = new ArrayList<Object>();//航班对象，直飞时只有一个对象
		
		singleLeg.put("legId", leg.getInt("legIndex"));
		singleLeg.put("departureAirportCode", taskQueue.getFromCity());
		singleLeg.put("arrivalAirportCode", taskQueue.getToCity());
		singleLeg.put("utcDepartureTimestamp", leg.getJSONObject("departureTime").getLong("dateTime"));
		singleLeg.put("utcArrivalTimestamp", leg.getJSONObject("arrivalTime").getLong("dateTime"));
		singleLeg.put("stopCount", leg.getInt("stops"));
		singleLeg.put("totalDurationInMinutes", (leg.getJSONObject("arrivalTime").getLong("dateTime")
				-leg.getJSONObject("departureTime").getLong("dateTime"))/1000/60);
		singleLeg.put("legPosition", leg.getInt("legIndex"));
		singleLeg.put("segments", segments);
		JSONArray timelines = leg.getJSONArray("timeline");
		JSONObject singleLine = null;
		for(int i = 0 ; i < timelines.size()+1; i+=2){ //航班
			Map<String, Object> singleSegment = new HashMap<String, Object>();
			singleLine = timelines.getJSONObject(i);
			singleSegment.put("departureAirportCode",singleLine.getJSONObject("departureAirport").getString("code"));
			singleSegment.put("arrivalAirportCode",singleLine.getJSONObject("arrivalAirport").getString("code"));
			singleSegment.put("carrierCode",singleLine.getJSONObject("carrier").getString("airlineCode"));
			singleSegment.put("operatingCarrierCode", singleLine.getJSONObject("carrier").getString("operatedByAirlineCode"));
			singleSegment.put("flightNumber", singleLine.getJSONObject("carrier").getString("flightNumber"));
			singleSegment.put("totalDurationInMinutes", (
					singleLine.getJSONObject("arrivalTime").getLong("dateTime")-
					singleLine.getJSONObject("departureTime").getLong("dateTime"))/1000/60);
			singleSegment.put("utcDepartureTimestamp", singleLine.getJSONObject("departureTime").getLong("dateTime"));
			singleSegment.put("utcArrivalTimestamp", singleLine.getJSONObject("arrivalTime").getLong("dateTime"));
			singleSegment.put("stopOver", "false");
			
			segments.add(singleSegment);
		}
		
		flight3.put("legs", legs);
		legs.add(singleLeg);
		entity.put("flight", flight1);
		logger.info("组装出的请求JSON参数:"+json.toString());
		return URLEncoder.encode(json.toString(), "utf-8") ;
	}
	/**
	 * 解析去程
	 * @param stops
	 * @return
	 * @throws Exception 
	 */
	private List<DoublePlaneInfoEntity> parseGoInfo(JSONArray ja, boolean stops) throws Exception{
		List<DoublePlaneInfoEntity> results = new ArrayList<DoublePlaneInfoEntity>();
		JSONObject departureTime = null, arrivalTime = null, duration = null;
		JSONObject price = null; //打包价格
		JSONObject j = null;
		List<TransitEntity> transits = null;
		DoublePlaneInfoEntity doublePlaneinfo = null;
		try{
			for(int i = 0; i < ja.size(); i++){
				j = ja.getJSONObject(i).getJSONArray("legs").getJSONObject(0);
				//只要中转，或直达,这里是过滤中转，或者直达都只要一条数据
				if((stops && j.getInt("stops")==0) || (!stops && j.getInt("stops")>0)) continue;
				price = j.getJSONObject("price");
				departureTime = j.getJSONObject("departureTime");
				arrivalTime = j.getJSONObject("arrivalTime");
				duration = j.getJSONObject("duration");
				transits = this.parseGoTrantsInfo(j);
				
				doublePlaneinfo = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, transits.get(0).getCarrierKey(),
						transits.get(0).getCarrierName(), transits.get(0).getCarrierFullName(), 
						null, null, transits.get(0).getFlightNo(), null, 
						null, null, transits.get(0).getFlightType(), DoublePlaneInfoEntity.class);
				doublePlaneinfo.setStartTime(new Date(departureTime.getLong("dateTime")));
				doublePlaneinfo.setEndTime(new Date(arrivalTime.getLong("dateTime")));
				doublePlaneinfo.setSumLowestPrice(price.getDouble("offerPrice"));
				doublePlaneinfo.setCurrency(price.getString("currencyCode"));
				doublePlaneinfo.setFlightDuration(duration.getLong("numOfDays")*24*3600*1000+
						duration.getLong("hours")*3600*1000+
						duration.getLong("minutes")*60*1000);
				//设置航班对象
				doublePlaneinfo.setTransits((ArrayList) transits);
				
				//获取返程数据
				if(IS_FETCH_RETURN) 
					doublePlaneinfo.getReturnPlaneInfos().addAll(this.fetchReturn(j));

				results.add(doublePlaneinfo);
				break;//目前只获得第一个，航线最低价即可,2014-09-04
			}
		}finally{
			 departureTime = null;
			 arrivalTime = null;
			 price = null; //打包价格
			 j = null;
			 transits = null;
			 doublePlaneinfo = null;
		}
		return results;
	}
	/**
	 * 解析返程
	 * @return
	 * @throws Exception 
	 */
	private List<ReturnDoublePlaneInfoEntity> parseReturnInfo(JSONArray ja) throws Exception{
		List<ReturnDoublePlaneInfoEntity> results = new ArrayList<ReturnDoublePlaneInfoEntity>();
		JSONObject departureTime = null, arrivalTime = null, duration = null;
		JSONObject price = null; //打包价格
		JSONObject j = null;
		List<ReturnTransitEntity> transits = null;
		ReturnDoublePlaneInfoEntity doublePlaneinfo = null;
		try{
			logger.info(String.format("获得的返程航班数量:[%s]", ja.size()));
			for(int i = 0; i < ja.size(); i++){
				j = ja.getJSONObject(i).getJSONArray("legs").getJSONObject(0);
				price = j.getJSONObject("price");
				departureTime = j.getJSONObject("departureTime");
				arrivalTime = j.getJSONObject("arrivalTime");
				duration = j.getJSONObject("duration");
				
				transits = this.parseReturnTrantsInfo(j);
	
				doublePlaneinfo = PlaneInfoEntityBuilder.buildPlaneInfo(taskQueue, transits.get(0).getCarrierKey(),
						transits.get(0).getCarrierName(), transits.get(0).getCarrierFullName(), 
						null, null, transits.get(0).getFlightNo(), null, 
						null, null, transits.get(0).getFlightType(), ReturnDoublePlaneInfoEntity.class);
				doublePlaneinfo.setStartTime(new Date(departureTime.getLong("dateTime")));
				doublePlaneinfo.setEndTime(new Date(arrivalTime.getLong("dateTime")));
				doublePlaneinfo.setSumLowestPrice(price.getDouble("offerPrice"));
				doublePlaneinfo.setCurrency(price.getString("currencyCode"));
				doublePlaneinfo.setFlightDuration(duration.getLong("numOfDays")*24*3600*1000+
						duration.getLong("hours")*3600*1000+
						duration.getLong("minutes")*60*1000);
				//设置航班对象
				doublePlaneinfo.setReturnTransits((ArrayList) transits);
				
				results.add(doublePlaneinfo);
			}
		}finally{
			 departureTime = null;
			 arrivalTime = null;
			 price = null; //打包价格
			 j = null;
			 transits = null;
			 doublePlaneinfo = null;
		}
		return results;
	}
	/**
	 * 解析去程中转(只有一个对象时，为直达)
	 * @param table
	 * @return
	 * @throws Exception 
	 */
	private List<TransitEntity> parseGoTrantsInfo(JSONObject timeline) throws Exception{
		List<TransitEntity> transits = new ArrayList<TransitEntity>();
		JSONArray transitsArray = timeline.getJSONArray("timeline"); //中转数组
		TransitEntity transitEntity = null;
		JSONObject transitObj = null;
		for(int i = 0 ;i < transitsArray.size(); i++){
			transitObj = transitsArray.getJSONObject(i);
			transitEntity = PlaneInfoEntityBuilder.buildTransitEntity(
					transitObj.getJSONObject("carrier").getString("airlineCode")+
					transitObj.getJSONObject("carrier").getString("flightNumber"), //航班号
					null, transitObj.getJSONObject("carrier").getString("airlineCode"), //航空公司二字编码
					transitObj.getJSONObject("carrier").getString("airlineName"), //航空公司简称
					transitObj.getJSONObject("carrier").getString("airlineName"), //航空公司全称
					transitObj.getJSONObject("departureAirport").getString("code"), 
					transitObj.getJSONObject("departureAirport").getString("city"), 
					transitObj.getJSONObject("arrivalAirport").getString("code"), 
					transitObj.getJSONObject("arrivalAirport").getString("city"), 
					transitObj.getJSONObject("carrier").getString("plane"));
			transitEntity.setCabinName(transitObj.getJSONObject("carrier").getString("bookingCode"));
			transitEntity.setStartTime(new Date(transitObj.getJSONObject("departureTime").getLong("dateTime")));
			transitEntity.setEndTime(new Date(transitObj.getJSONObject("arrivalTime").getLong("dateTime")));
			//停留时长对象, i++双数的对象为中转停留时长对象，所以再加1
			transitObj = transitsArray.getJSONObject(i++);
			transitEntity.setStayTime(
				transitObj.getJSONObject("duration").getLong("numOfDays")*24*3600*1000+
				transitObj.getJSONObject("duration").getLong("hours")*3600*1000+
				transitObj.getJSONObject("duration").getLong("minutes")*60*1000);
		   transits.add(transitEntity);
		}
		return transits;
	}
	
	/**
	 * 解析返程中转
	 * @param table
	 * @return
	 * @throws Exception 
	 */
	private List<ReturnTransitEntity> parseReturnTrantsInfo(JSONObject timeline) throws Exception{
		List<ReturnTransitEntity> transits = new ArrayList<ReturnTransitEntity>();
		JSONArray transitsArray = timeline.getJSONArray("timeline"); //中转数组
		ReturnTransitEntity transitEntity = null;
		JSONObject transitObj = null;
		for(int i = 0 ;i < transitsArray.size(); i++){
			transitObj = transitsArray.getJSONObject(i);
			transitEntity = PlaneInfoEntityBuilder.buildReturnTransitEntity(
					transitObj.getJSONObject("carrier").getString("airlineCode")+
					transitObj.getJSONObject("carrier").getString("flightNumber"), //航班号
					null, transitObj.getJSONObject("carrier").getString("airlineCode"), //航空公司二字编码
					transitObj.getJSONObject("carrier").getString("airlineName"), //航空公司简称
					transitObj.getJSONObject("carrier").getString("airlineName"), //航空公司全称
					transitObj.getJSONObject("departureAirport").getString("code"), 
					transitObj.getJSONObject("departureAirport").getString("city"), 
					transitObj.getJSONObject("arrivalAirport").getString("code"), 
					transitObj.getJSONObject("arrivalAirport").getString("city"), 
					transitObj.getJSONObject("carrier").getString("plane"));
			transitEntity.setCabinName(transitObj.getJSONObject("carrier").getString("bookingCode"));
			transitEntity.setStartTime(new Date(transitObj.getJSONObject("departureTime").getLong("dateTime")));
			transitEntity.setEndTime(new Date(transitObj.getJSONObject("arrivalTime").getLong("dateTime")));
			//停留时长对象, i++双数的对象为中转停留时长对象，所以再加1
			transitObj = transitsArray.getJSONObject(i++);
			transitEntity.setStayTime(
				transitObj.getJSONObject("duration").getLong("numOfDays")*24*3600*1000+
				transitObj.getJSONObject("duration").getLong("hours")*3600*1000+
				transitObj.getJSONObject("duration").getLong("minutes")*60*1000);
		   transits.add(transitEntity);
		}
		return transits;
	}
}
